package com.tonysong.oa.yeboa12.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tonysong.oa.yeboa12.config.domain.Login;
import com.tonysong.oa.yeboa12.config.util.JwtTokenUtil;
import com.tonysong.oa.yeboa12.config.util.R;
import com.tonysong.oa.yeboa12.config.util.RedisCache;
import com.tonysong.oa.yeboa12.pojo.Admin;
import com.tonysong.oa.yeboa12.mapper.AdminMapper;
import com.tonysong.oa.yeboa12.pojo.Role;
import com.tonysong.oa.yeboa12.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tonysong
 * @since 2022-12-01
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    //操作jwt和redis
    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private RedisCache redisCache;

    @Value("${jwt.tokenHead}")//Bearer
    private String tokenHead;
    @Resource
    private PasswordEncoder passwordEncoder;


    @Resource
    private AdminMapper adminmapper;

    @Override
    public R login(Login login) {
        System.out.println("###进入了AdminService的登录的业务处理#");
        //首先判断验证码是否过期和有效
        //从Redis中获取
        String captcha = this.redisCache.getCacheObject("captcha");
        if(Objects.isNull(captcha) || !Objects.equals(captcha, login.getCode())){
            return  new R(400, false, "验证码无效，登录过期！");
        }
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(login.getUsername());
        //如果为null在抛出异常
        if(Objects.isNull(userDetails) || !this.passwordEncoder.matches(login.getPassword(), userDetails.getPassword())){
            throw new UsernameNotFoundException("错误的账号或密码,登录失败！");
        }
       //保存登录状态到
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = this.jwtTokenUtil.generateToken(userDetails);
        Map<String,Object> map= new HashMap<>();
        map.put("tokenHead",this.tokenHead);
        map.put("token",token);//存储了用户信息（）
        // 返回数据给前台！
        return new R(200,Boolean.TRUE,"登录成功",map);
    }

    @Override
    public List<Role> findRoles(Integer id) {
        return this.adminmapper.findRoles(id);
    }
}
